<?php
namespace app\common\model\member;

use app\common\model\BaseModel;

class AccountModel extends BaseModel
{
    protected $name = 'member_account';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 搜索器
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchViewAttr($query, $value, $data){
        //主表
        if(in_array('member_account',$value)){
            $fields = $this->getTableFields('member_account');
            $query->view('member_account',$fields);
        }
        //关联表
        if(in_array('member',$value)){
            $query->view('member','username,nickname,mobile,email,qq','member_account.member_id=member.id','LEFT');
        }
    }

    /**
     * 添加
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addData($data) {
        $time = time();
        $userinfo = MemberModel::where('id',$data['member_id'])->find();
        if(empty($userinfo)) exception('未找到该会员！');
        if($data['change_type']==2){ //提现
            if ($data['amount'] > $userinfo['amount']) {
                exception('提现金额大于会员可用金额！');
            }
            $data['amount'] = $data['amount']*-1; //提现为负
        }
        $data['create_time'] = $time;
        $data['change_time'] = $time;
        self::create($data,true);
        if($data['is_pay'] == 1) { //记录资金明细
            $changeDesc = $data['change_type']==2 ? '账户提现' : '账户充值';
            $changeLogModel = new ChangeLogModel();
            $changeLogModel->change($userinfo['id'],['amount'=>$data['amount']],$data['change_type'],$changeDesc);
        }
    }
    /**
     * 编辑
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editData($data){
        $account = $this->where('id',$data['id'])->find();
        if($account['is_pay']==1) exception('已付款不允许修改！');
        $data['change_time'] = time(); //更新时间
        $data['amount'] = $account['change_type']==1 ? $data['amount'] : $data['amount']*-1; //提现为负
        self::update($data,[],true);
        $changeDesc = $account['change_type']==1 ? '账户充值' : '账户提现';
        $changeLogModel = new ChangeLogModel();
        $changeLogModel->change($account['member_id'],['amount'=>$data['amount']],$account['change_type'],$changeDesc);
    }

}